package com.aps.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aps.entity.domain.dish.DishTypeSeq;
import com.aps.entity.dto.ApsOrderDishDbDTO;
import com.aps.entity.dto.PosSyncDishType;
import com.aps.service.IDishTypeSeqService;
import com.aps.service.rep.DishTypeSeqRep;

/**
 * @author liaoguangan
 * @description <>
 * @date 2018/4/2 12:03
 */
@Service
public class DishTypeSeqServiceiImpl implements IDishTypeSeqService {

    @Autowired
    private DishTypeSeqRep dishTypeSeqRep;

    /**
     * 排序
     *
     * @param list
     */
    @Override
    public void sort(List<ApsOrderDishDbDTO> list) {

        //设置优先级
        ApsOrderDishDbDTO first = null; //指定先上菜品
        for (ApsOrderDishDbDTO apsOrderDishDbDTO : list) {
            apsOrderDishDbDTO.setPriority(dishTypeSeqRep
                    .findByCode(apsOrderDishDbDTO.getDish().getDishTypeCode()).getSequence());

            if (apsOrderDishDbDTO.getOrderDish().getIsFirst()) {
                first = apsOrderDishDbDTO;
            }
        }

        //是否指定菜品先上
        if (null != first) {
            first.setPriority(-1); //保证优先级数字最小
        }

        //排序
        Collections.sort(list, new Comparator<ApsOrderDishDbDTO>() {

            @Override
            public int compare(ApsOrderDishDbDTO o1, ApsOrderDishDbDTO o2) {
                int temp = o1.getPriority() - o2.getPriority();
                return temp > 0 ? 1 : -1;
            }
        });

        //设置每个订单的第一个菜品标志位
        if (null != list && list.size() > 0) {
            list.get(0).setIsFirst(true);
        }
    }

    /**
     * 同步菜品类别信息
     *
     * @param posSyncDishType
     */
    @Override
    public void save(List<PosSyncDishType> posSyncDishType) {
        List<DishTypeSeq> dishes = new ArrayList<>();
        for (PosSyncDishType d : posSyncDishType) {
            dishes.add(d.build());
        }
        dishTypeSeqRep.save(dishes);
    }
}
